﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.DTO;
using ZSZ.Iservice;
using ZSZ.Service.Entity;

namespace ZSZ.Service
{
    public class SettingService : ISettingService
    {
        private SettingDTO ToDTO(SettingEntity e) {
            SettingDTO dto = new SettingDTO();
            dto.CreateTime = e.CreateDatatime;
            dto.Id = e.Id;
            dto.Name = e.Name;
            dto.Value = e.Value;
            return dto;
        }
        public SettingDTO[] GetAll()
        {
            using (ZSZDBcontext ct = new ZSZDBcontext())
            {
                CommonService<SettingEntity> cs = new CommonService<SettingEntity>(ct);
                return cs.GetAll().Select(c=>ToDTO(c)).ToArray();
            }
        }

        public string GetValue(string name)
        {
            using (ZSZDBcontext ct = new ZSZDBcontext())
            {
                CommonService<SettingEntity> cs = new CommonService<SettingEntity>(ct);
                var setting = cs.GetAll().SingleOrDefault(s=>s.Name==name);
                if (setting==null)
                {
                    throw new ArgumentException("没有这个配置");
                }
                return setting.Value;
            }
        }

        public void SetValue(string name, string value)
        {
            using (ZSZDBcontext ct = new ZSZDBcontext())
            {
                CommonService<SettingEntity> cs = new CommonService<SettingEntity>(ct);
                var setting = cs.GetAll().SingleOrDefault(s => s.Name == name);
                if (setting != null)
                {
                    throw new ArgumentException("已经有这个配置了");
                }
                SettingEntity en = new SettingEntity();
                en.Name = name;
                en.Value = value;
                ct.Settings.Add(en);
                ct.SaveChanges();
            }
        }
    }
}
